package com.asianrapid.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @Auther: 迟家鑫
 * @Date: 2018/6/19 13:42
 * @Description: MD5加密工具类
 */
public class MD5Utils {
	private static Logger logger = LoggerFactory.getLogger(MD5Utils.class);

	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    //加的盐
    private static final String SALT = "CXWcjvILHE1wI8YTEsLZpS0pWj59A36Kd";

	/**
	 * 将传递的字符串进行MD5加密
	 * @param source 需要加密的字符串
	 * @return
	 */
    public static String encryptMD5(String source) {
    	try {
			MessageDigest digist = MessageDigest.getInstance("MD5");
			byte[] rs = digist.digest(source.getBytes());
			StringBuffer digestHexStr = new StringBuffer();
	          for (int i = 0; i < 16; i++) {
	        	  digestHexStr.append(byteHEX(rs[i]));
	          }
	          return digestHexStr.toString();
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage(),e);
		}
    	return null;

    }

	/**
	 * 功能：得到文件的md5值。
	 *
	 * @author 宋立君
	 * @date 2014年06月24日
	 * @param file
	 *            文件。
	 * @return String
	 * @throws IOException
	 *             读取文件IO异常时。
	 */
	public static String getFileMD5String(File file) throws IOException, NoSuchAlgorithmException {
		FileInputStream in = new FileInputStream(file);
		FileChannel ch = in.getChannel();
		MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
				file.length());
		MessageDigest digist = MessageDigest.getInstance("MD5");
		digist.update(byteBuffer);
		return bufferToHex(digist.digest());
	}

	/**
     * 加盐的md5值。这样即使被拖库，仍然可以有效抵御彩虹表攻击
     * @param source 需要加密的字符串
     * @return
     *
     */
    public static String encryptMD5AndSalt(String source) {
        return encryptMD5(encryptMD5(source) + SALT);
    }

	/**
	 * byte转换为字符串的方法
	 * @param ib 需要转换成String的byte
	 * @return
	 */
    private static String byteHEX(byte ib) {
    	char [] ob = new char[2];
    	ob[0] = hexDigits[(ib >>> 4) & 0X0F];
    	ob[1] = hexDigits[ib & 0X0F];
    	String s = new String(ob);
    	return s;
    }

	/**
	 * byte转换为字符串的方法
	 * @param bytes 需要转换成String的byte[]
	 * @return
	 */
	private static String bufferToHex(byte bytes[]) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private static String bufferToHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			appendHexPair(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}

	private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}
}
